﻿using DeviceController.Wpf.Common;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Windows;

namespace DeviceController.Wpf.Core
{
    internal static class ServiceProviderExtensions
    {
        public static TView GetViewService<TView, TViewModel>(this IServiceProvider services) where TView : Window where TViewModel : notnull
        {
            var view = services.GetRequiredService<TView>();
            view.DataContext = services.GetRequiredService<TViewModel>();

            if (view.DataContext is IViewAware aware)
            {
                view.Closing += (s, args) =>
                {
                    args.Cancel = !aware.CanClose();
                };

                // 创建一个临时的委托，委托闭包引用了 aware，所以不会造成内存泄漏。
                // 如果 view 不释放，那么委托不会释放，间接导致 aware 不会被释放。
                view.Closed += (s, args) =>
                {
                    aware.OnClosed();
                };
            }

            return view;
        }
    }
}
